﻿using MediatR; 

namespace MediatRApp.Commands
{
    public class TrsanctionPipelineBehavior<TResult, TResponse> : IPipelineBehavior<TResult, TResponse> where TResult : notnull
    {
        private readonly DbContext _context;
        public TrsanctionPipelineBehavior(DbContext context)
        {
            this._context = context;
        }
        public async Task<TResponse> Handle(TResult request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            TResponse? response;
            try
            {
                if (_context.HasActiveTransaction)
                {
                    return await next();
                }
                else
                {
                    using (var transction = _context.BeginTransction())
                    {
                        response = await next();
                        _context.CommitTransction();
                    }
                }
            }
            catch (Exception)
            { 
                throw;
            } 
            return response;
        }
    }

}